from flask import Blueprint, current_app, jsonify, session, request, json
from app.utils.code import RET
from app.utils.common import login_required
from app.utils.util import create_order_sn
from app.models import HouseModel, OrderModel
from app import db
import datetime

api_order = Blueprint("api_order", __name__)

''' 添加订单 '''
@api_order.route("/orders", methods=["POST"])
def add_order():
    json_dict = request.get_json()
    house_id = json_dict.get("house_id")
    start_date = json_dict.get("start_date")
    end_date = json_dict.get("end_date")

    if not all([house_id, start_date, end_date]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 日期格式检查
    try:
        # 将请求的时间参数字符串转换为datetime类型
        start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
        assert start_date <= end_date
        # 计算预订的天数
        days = (end_date - start_date).days + 1  # datetime.timedelta
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="日期格式错误")

    # 判断房屋是否存在
    try:
        house = HouseModel.query.filter_by(id=house_id, is_deleted=0).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库异常")

    if house is None:
        return jsonify(errno=RET.PARAMERR, errmsg="房屋不存在")
    
    if session['user_id'] == house.user_id:
        return jsonify(errno=RET.DATAREPEAT, errmsg="不能预订自己的房屋")
    
    # 判断房屋是否被订购
    try:
        count = OrderModel.query.filter(OrderModel.house_id==house_id, OrderModel.begin_date <= end_date, OrderModel.end_date >= start_date).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="检查出错，请稍候重试")
    
    if count > 0:
        return jsonify(errno=RET.DATAERR, errmsg="房屋已被预订")

    # 订单总额
    amount = days * house.price

    # 保存订单数据
    order = OrderModel(
        no = create_order_sn(),
        house_id=house_id,
        user_id=session['user_id'],
        begin_date=start_date,
        end_date=end_date,
        days=days,
        house_price=house.price,
        amount=amount
    )
    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存订单失败")
    return jsonify(errno=RET.OK, errmsg="OK", data={"order_id": order.id})

''' 设置订单状态 '''
@api_order.route("/orders/<order_id>/status", methods=["PUT"])
@login_required
def set_order_status(order_id):
    json_dict = request.get_json()
    action = json_dict.get('action')

    if not order_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    try:
        # 根据订单号查询订单，并且要求订单处于等待接单状态
        order = OrderModel.query.filter(OrderModel.id == order_id, OrderModel.status == 0).first()
        house = order.house
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="无法获取订单数据")

    user_id = session['user_id']

    # 确保房东只能修改属于自己房子的订单
    if not order or house.user_id != user_id:
        return jsonify(errno=RET.REQERR, errmsg="操作无效")

    if action == "accept":
        # 接单，将订单状态设置为待支付
        order.status = 1
    elif action == "reject":
        # 拒单，要求用户传递拒单原因
        reason = json_dict.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        order.status = 6
        order.comment = reason

    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="操作失败")

    return jsonify(errno=RET.OK, errmsg="OK")

''' 去支付 '''
@api_order.route('/orders/<order_id>/payment', methods=["POST"])
@login_required
def pay_order(order_id):
    if not order_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    user_id = session['user_id']
    # 判断订单状态
    try:
        order = OrderModel.query.filter(OrderModel.id == order_id, OrderModel.user_id == user_id, OrderModel.status == 1).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    if order is None:
        return jsonify(errno=RET.DATANOTEXIST, errmsg="订单数据有误")
    
    ''' 调用支付宝处理支付问题 '''

    return jsonify(errno=RET.OK, errmsg="支付成功")

''' 设置订单支付后的状态 '''
@api_order.route('/orders/payment', methods=["PUT"])
def save_order_result():
    order_id = request.form.get("oid")

    if not order_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        OrderModel.query.filter_by(id=order_id).update({"status": 3})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

    return jsonify(errno=RET.OK, errmsg="OK")

''' 订单评价 '''
@api_order.route("/orders/<order_id>/comment", methods=["PUT"])
@login_required
def order_comment(order_id):
    json_dict = request.get_json()
    comment = json_dict.get('comment')

    if not all([comment, order_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    try:
        order = OrderModel.query.filter(OrderModel.id==order_id, OrderModel.status==3).first()
        house = order.house
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    if not order:
        return jsonify(errno=RET.DATANOTEXIST, errmsg="操作无效")
    
    try:
        # 设置订单状态为：完成
        order.status = 4
        order.comment = comment
        # 设置房源的订单量
        house.order_count += 1
        db.session.add(order)
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="操作失败")

    return jsonify(errno=RET.OK, errmsg="评价成功")